﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Net;

using SBK.SMSGateway.Biz;
using SBK.SMSGateway.Entities.Models;
using SBK.SMSGateway.Entities.Utils;
using SBK.SMSGateway.Utilities;

namespace SBK.SMSGateway
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        /// <summary>
        /// Nhan tin nhan MO tu nha cung cap NEO va gui tin nhan MT chu dong cho khach
        /// </summary>
        [WebMethod]
        public int ReceiveMoAndSendMt(string user_Id, string service_Id, string command_Code, string message, string request_Id, string rvUsername, string rvPassword)
        {
            LogFile.SaveReceiverMOLog("MO: -> So gui: " + user_Id + " | So nhan: " + service_Id + " | Noi dung: " + message + " | MessageId: " + request_Id);
            return SMSRoutingSevices(user_Id, service_Id, command_Code, message, request_Id, rvUsername, rvPassword);
        }

        /// <summary>
        /// Tu dong xu ly va gui tin nhan MT cho khach
        /// </summary>
        [WebMethod]
        public int AutoSMS(string user_Id, string service_Id, string command_Code, string message, string request_Id, string rvUsername, string rvPassword)
        {
            LogFile.SaveReceiverMOLog("AutoSMS: -> So gui: " + user_Id + " | So nhan: " + service_Id + " | Noi dung: " + message + " | MessageId: " + request_Id);
            return SMSRoutingSevices(user_Id, service_Id, command_Code, message, request_Id, rvUsername, rvPassword);
        }

        /// <summary>
        /// Function sender SMS
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public int SendSMS(string userId, string message, string serviceId, string commandCode, string requestID, string contentType, string MTusername, string MTpassword)
        {
            int count = 0;
            int MT = 0;
            do
            {
                int[] arrRetry = new int[1] { -1 };//mang chua ma loi can retry tu SBK
                MT = new MessageMT().SendMT(userId, message, serviceId, commandCode, requestID, contentType, MTusername, MTpassword);
                string ms = MT.ToString() + " - Success";
                if (MT != 0) ms = MT.ToString() + " - Failed";
                LogFile.SaveSendMTLog("So gui: " + serviceId + " | So nhan: " + userId + " | Noi dung: " + message + " | KQ gui tin: " + ms);
                try
                {
                    if (Array.BinarySearch(arrRetry, MT) >= 0)
                        count += 1;
                    else
                        count = 6;
                }
                catch
                {
                    count += 1;
                }
            }
            while (count < 5);
            return MT;
        }

        /// <summary>
        /// Nhan tin nhan MO va gui tin nhan MT
        /// </summary>
        /// <param>String user_Id: Số di động gửi đến theo chuẩn international, bắt đầu bằng 84(Tham số lỗi 1)</param>
        /// <param>String service_Id: Số dịch vụ (Số mà ADA kết nối: 8xxx) (Tham số lỗi 2)</param>
        /// <param>String command_Code : Mã của dịch vụ (Tùy theo từng dịch vụ), mã này sẽ phục vụ cho việc thống kê và quản lý MT phát sinh. (Tham số lỗi 3)</param>
        /// <param>String message: Nội dung tin nhắn, nội dung tin nhắn mã hóa base64 trước khi truyền qua(sau khi giải mã có độ dài <= 160 ký tự, không hỗ trợ tiếng Việt có dấu0). (Tham số lỗi 4)</param>
        /// <param>String request_Id:  Mã yêu cầu của khách hàng gồm 8 chữ số, số này dùng cho việc xác định MT phản hồi cho MO này. (Tham số lỗi 5)</param>
        /// <param>String username: tên truy cập webservice do SBK cung cấp.</param>
        /// <param>String password: mật khẩu truy cập ws do SBK cung cấp.</param>
        /// <returns>
        /// -1: System error
        /// 0: Success
        /// Giá trị khác: Sai ở tham số nào thì trả về vị trí của tham số đó
        /// </returns>
        public int SMSRoutingSevices(string user_Id, string service_Id, string command_Code, string message, string request_Id, string rvUsername, string rvPassword)
        {
            int ErrorCode = -1;//Other
            MyConfig myconfig = new MyConfig();
            if (myconfig.GetMyConfig())
            {
                string[] arrMO = message.Split(' ');
                string Key = arrMO[0].Trim().ToUpper(); string SubKey = ""; string UserName = "";
                if (Key == myconfig.KeyWord)
                {
                    try { SubKey = arrMO[1].Trim().ToUpper(); }
                    catch { SubKey = null; }
                    if (!string.IsNullOrEmpty(SubKey))
                    {
                        string[] arrService = new string[6] { "BTMC", "KH", "SBJ", "SJC", "TG", "VN" };//Array initialization service
                        if (Array.BinarySearch(arrService, SubKey) >= 0)//SubKey array of services
                        {
                            string result = null;
                            switch (SubKey)
                            {
                                case "KH"://Activation forum
                                    try { UserName = arrMO[2].Trim(); }
                                    catch { UserName = ""; }
                                    if (new AuthorService().SelectWithUserName(UserName).Count == 0)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, myconfig.rptAuthenFail, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                        break;
                                    }
                                    AuthorInfo aUthorInfo = new AuthorInfo();
                                    aUthorInfo.UserName = UserName;
                                    aUthorInfo.Active = true;
                                    new AuthorService().Update(aUthorInfo);
                                    ErrorCode = this.SendSMS(user_Id, myconfig.rptSuccessful, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    break;
                                case "TG"://Return world Gold
                                    result = new WebClient().DownloadString(myconfig.urlWorldGold);
                                    if (result.Trim().Length != 0 && result.Trim().Length <= myconfig.MaximumLengthSMSofGold)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, result, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    }
                                    else
                                    {
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport1, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport2, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                    }
                                    break;
                                case "VN"://Return VN gold
                                    result = new WebClient().DownloadString(myconfig.urlVNGold);
                                    if (result.Trim().Length != 0 && result.Trim().Length <= myconfig.MaximumLengthSMSofGold)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, result, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    }
                                    else
                                    {
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport1, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport2, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                    }
                                    break;
                                case "SJC"://Return SJC gold
                                    result = new WebClient().DownloadString(myconfig.urlSJCGold);
                                    if (result.Trim().Length != 0 && result.Trim().Length <= myconfig.MaximumLengthSMSofGold)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, result, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    }
                                    else
                                    {
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport1, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport2, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                    }
                                    break;
                                case "BTMC"://Return BTMC gold
                                    result = new WebClient().DownloadString(myconfig.urlBTMCGold);
                                    if (result.Trim().Length != 0 && result.Trim().Length <= myconfig.MaximumLengthSMSofGold)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, result, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    }
                                    else
                                    {
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport1, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport2, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                    }
                                    break;
                                case "SBJ"://Return SBJ gold
                                    result = new WebClient().DownloadString(myconfig.urlSBJGold);
                                    if (result.Trim().Length != 0 && result.Trim().Length <= myconfig.MaximumLengthSMSofGold)
                                    {
                                        ErrorCode = this.SendSMS(user_Id, result, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                                    }
                                    else
                                    {
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport1, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                        ErrorCode = this.SendSMS(myconfig.PhoneSuport2, myconfig.rptDataPrice, myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                                    }
                                    break;
                            }
                        }
                        else
                        {
                            ErrorCode = this.SendSMS(user_Id, myconfig.rptStructureError, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                        }
                    }
                    else
                    {
                        ErrorCode = this.SendSMS(user_Id, myconfig.Suport, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                    }
                }
                else
                {
                    ErrorCode = this.SendSMS(user_Id, myconfig.rptStructureError, service_Id, command_Code, request_Id, myconfig.ContentType, rvUsername, rvPassword);
                }
            }
            else
            {
                ErrorCode = this.SendSMS("0979539526", "SMSGateway config error, check now!!!", myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
                ErrorCode = this.SendSMS("0979539526", "SMSGateway config error, check now!!!", myconfig.ServiceID, myconfig.CommandCode, myconfig.RequestID, myconfig.ContentType, myconfig.rvUserName, myconfig.rvPassword);
            }
            return ErrorCode;
        }
    }
}
